package com.itheima.dubbo.api;

import com.itheima.dubbo.util.IdSequence;
import com.tanhua.domain.mogo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.PublishApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service
public class PublicApiImpl implements PublishApi {

   @Autowired
   private MongoTemplate mongoTemplate;
   @Autowired
   private IdSequence idSequence;

   //更新审核状态
    @Override
    public void updateState(Publish publish) {
        Query query = new Query(Criteria.where("id").is(publish.getId()));
        Update update = new Update().set("state", publish.getState());
        mongoTemplate.updateFirst(query,update,Publish.class);

    }

    @Override
    public List<Publish> findPublishListByPids(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));

        return mongoTemplate.find(query,Publish.class);
    }

    @Override
    public String save(Publish publish) {
   //1.把动态存储到动态publish里
        publish.setId(ObjectId.get());
        publish.setPid(idSequence.getNextId("quanzi_publish"));
        publish.setCreated(System.currentTimeMillis());
        mongoTemplate.save(publish);

        //2.把动态存储到当前用户的相册表quanzi_album_用户id
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.save(album,"quanzi_album_"+publish.getUserId());

    //3.把动态插入到当前用户好友的时间线里quanzi_timeline_好友id

        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        for (Friend friend : friends) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publish.getId());
            timeLine.setUserId(publish.getUserId());
            timeLine.setCreated(System.currentTimeMillis());
            Long friendId = friend.getFriendId();
            mongoTemplate.save(timeLine,"quanzi_time_line_"+friendId);

        }
        return publish.getId().toHexString();

    }


    @Override
    public PageResult<Publish> findByTimeline(int page, int pagesize, long userId) {
        //查询当前用户的时间线（时间线里是好友的动态列表）
        Query query=new Query().with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        //数量
        long count = mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);

        //把时间线里的publishId 转换成对应的Publish对象
        List<Publish> publishList = new ArrayList<>(timeLines.size());
        for (TimeLine timeLine : timeLines) {
            ObjectId publishId = timeLine.getPublishId();
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            publishList.add(publish);
        }
        //封装分页结果
        int pages= (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int) count,pagesize,pages,page,publishList);
    }



    @Override
    public PageResult<Publish> findByRecommend(int page, int pagesize, long userId) {
        //查询给userId推荐的动态列表
        Query query=Query.query(Criteria.where("userId").is(userId)
        .and("publishId").ne(null))
                .with(PageRequest.of(page-1,pagesize));
        List<RecommendQuanZi> quanziList = mongoTemplate.find(query, RecommendQuanZi.class);

        long count = mongoTemplate.count(query, RecommendQuanZi.class);

        //2.把推荐publishId，转换成对应的publish
        ArrayList<Publish> publishList = new ArrayList<>();
        for (RecommendQuanZi quanZi : quanziList) {
            Publish publish = mongoTemplate.findById(quanZi.getPublishId(), Publish.class);
           publishList.add(publish);
        }
        //3.封装分页结果
        int pages= (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int) count,pagesize,pages,page,publishList);

    }

    /**
     * 查询一条动态
     * @param publishId 动态id
     * @return publishId对应的Publish对象
     */
    @Override
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId ),Publish.class);
    }


    /**
     * 分页查询动态列表
     * @param page 页码
     * @param pagesize 查询几条
     * @param uid 用户id
     * @param state 动态的审核状态
     * @return 分页查询结果
     */
    @Override
    public PageResult<Publish>findPublishList(int page, int pagesize, Long uid, String state) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        if (uid!=null){
            query.addCriteria(Criteria.where("userId").is(uid));

        }
        if (state!=null&&!"".equals(state)){
            query.addCriteria(Criteria.where("state").is(state));

        }
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        long count=mongoTemplate.count(query,Publish.class);
        int pages=(int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int)count,page,pagesize,pages,publishList);

    }

    //查询相册-查询某一用户的相册（动态）
    @Override
    public PageResult<Publish> findAlbumList(int page, int pagesize, long userId) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        long count=mongoTemplate.count(query,Album.class,"quanzi_album_"+userId);
        List<Publish> publishList = new ArrayList<>();
        for (Album album : albumList) {
            Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
            publishList.add(publish);
        }
        int pages= (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int) count,pagesize,pages,page,publishList);

    }
}
